module.exports = (app) => {
  const express = require('express')
  const router = express.Router({ mergeParams: true })
  const multer = require('multer')
  const upload = multer({ dest: __dirname + '/../../uploads' })

  // 上传资源保存数据
  router.post('/', async (req, res) => {
    const model = await req.Model.create(req.body)
    res.send(model)
  })

  // 获取所有资源
  router.get('/', async (req, res) => {
    const queryOptions = {}
    if (req.Model.modelName === 'Category') {
      queryOptions.populate = 'parent'
    }
    if (req.Model.modelName === 'Course') {
      queryOptions.populate = 'category'
    }
    let model = await req.Model.find().setOptions(queryOptions).lean()
    console.log(model)
    const newData = model.map((v) => {
      v.key = v._id
      return v
    })
    console.log(newData)
    res.send(newData)
  })

  // 通过 id 获取指定资源
  router.get('/:id', async (req, res) => {
    const queryOptions = {}
    if (req.Model.modelName === 'Category') {
      queryOptions.populate = 'parent'
    }
    const model = await await req.Model.findById(req.params.id).setOptions(
      queryOptions
    )
    res.send(model)
  })

  // 通过 id 修改资源
  router.put('/:id', async (req, res) => {
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
    res.send(model)
  })

  // 通过 id 删除资源
  router.delete('/:id', async (req, res) => {
    const model = await req.Model.findByIdAndDelete(req.params.id)
    res.send(model)
  })

  // 通用接口处理
  app.use(
    '/admin/api/rest/:resource',
    async (req, res, next) => {
      const modelName = require('inflection').classify(req.params.resource)
      // 将 Model 挂载到 req 中，这样就能在子级路由中通过 req.Model 来获取
      req.Model = require(`../../models/${modelName}`)
      next()
    },
    router
  )

  // 获取课程数据的测试接口
  app.get('/init/list', async (req, res) => {
    const Category = require('../../models/Category')
    const Course = require('../../models/Course')

    const rawData = [
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/06474957ee46379003.jpg',
        title: 'Access 2007教程',
        metas: ['19万+浏览', '3529学员', '4.4评分'],
        author: {
          avatar:
            'http://image.howzhi.com/avatar/2012/05-22/0839197d9d4d936788.jpg',
          name: '狂凉',
          isVip: false
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/06475396f028488840.jpg',
        title: '幻影引擎3D游戏开发教程(易语言)',
        metas: ['12万+浏览', '1530学员', '4.2评分'],
        author: {
          avatar: 'http://www.howzhi.com/assets/img/default/avatar.png',
          name: '怪异癖好',
          isVip: false
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/064749595768453601.jpg',
        title: 'Flash MX视频讲座全集',
        metas: ['5296浏览', '67学员', '5评分'],
        author: {
          avatar:
            'http://image.howzhi.com/avatar/2012/05-28/0236480dad67320068.jpg',
          name: '神的回赠',
          isVip: false
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/0647495d85ea558884.jpg',
        title: 'Flash 8.0基础教程',
        metas: ['1万+浏览', '236学员', '4.6评分'],
        author: {
          avatar:
            'http://image.howzhi.com/avatar/2012/05-28/0236480dad67320068.jpg',
          name: '神的回赠',
          isVip: false
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/064750614c14799305.jpg',
        title: 'Flash8 入门到高手视频',
        metas: ['1万+浏览', '177学员', '5评分'],
        author: {
          avatar:
            'http://image.howzhi.com/avatar/2012/05-28/0236480dad67320068.jpg',
          name: '神的回赠',
          isVip: false
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/064751742376047869.jpg',
        title: 'Flash CS4动画设计与制作300例',
        metas: ['2万+浏览', '533学员', '4.6评分'],
        author: {
          avatar:
            'http://image.howzhi.com/avatar/2012/05-28/0236480dad67320068.jpg',
          name: '神的回赠',
          isVip: false
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/064751775cbc952829.jpg',
        title: 'Flash制作MV教程',
        metas: ['1万+浏览', '161学员', '3.7评分'],
        author: {
          avatar:
            'http://image.howzhi.com/avatar/2012/05-28/0236480dad67320068.jpg',
          name: '神的回赠',
          isVip: false
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/06522267d988983097.jpg',
        title: '密码学 ',
        metas: ['2万+浏览', '188学员', '5评分'],
        author: {
          avatar:
            'http://image.howzhi.com/avatar/2013/11-18/03140083ae94466017.jpg',
          name: '云江平',
          isVip: false
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/064752892a4c334501.jpg',
        title: '方正飞腾排版教程',
        metas: ['4万+浏览', '388学员', '4.8评分'],
        author: {
          avatar:
            'http://image.howzhi.com/avatar/2012/05-17/065458289634414448.jpg',
          name: 'Cross',
          isVip: true
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/065320080c66238110.jpg',
        title: 'iOS开发视频教程《C语言基础》',
        metas: ['7866浏览', '169学员', '3评分'],
        author: {
          avatar:
            'http://image.howzhi.com/user/2017/11-22/134011bf1d3a989141.jpg',
          name: '千锋教育',
          isVip: false
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/064754abc2fb670748.jpg',
        title: '从零开始学汇编',
        metas: ['13万+浏览', '2362学员', '4.7评分'],
        author: {
          avatar: 'http://www.howzhi.com/assets/img/default/avatar.png',
          name: '我爱好知网',
          isVip: false
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/06480115314e256336.jpg',
        title: '精通SPSS统计分析',
        metas: ['7931浏览', '299学员', '2.8评分'],
        author: {
          avatar:
            'http://image.howzhi.com/default/2015/07-14/145733d2af26635228.jpg',
          name: '乱流',
          isVip: true
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/0650444cd744855730.jpg',
        title: 'Unity3d游戏开发',
        metas: ['3万+浏览', '359学员', '4.8评分'],
        author: {
          avatar:
            'http://image.howzhi.com/avatar/2012/08-08/140516ce8476332134.jpg',
          name: 'drools',
          isVip: false
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/064739b70eb0327767.jpg',
        title: 'Linux 开发者基础教程',
        metas: ['1万+浏览', '302学员', '4.4评分'],
        author: {
          avatar:
            'http://image.howzhi.com/avatar/2011/09-02/0411120e080c849314.jpg',
          name: '轻步而来',
          isVip: true
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/0648033e5eca064381.jpg',
        title: '系统分析师视频教程',
        metas: ['3万+浏览', '617学员', '3.7评分'],
        author: {
          avatar:
            'http://image.howzhi.com/avatar/2012/05-17/065458289634414448.jpg',
          name: 'Cross',
          isVip: true
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2015/07-09/0653520d64e6896890.jpg',
        title: '【推荐】Mysql',
        metas: ['6334浏览', '218学员', '4.2评分'],
        author: {
          avatar:
            'http://image.howzhi.com/avatar/2014/10-12/06115170b6db164363.jpg',
          name: '被遗忘者',
          isVip: false
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2017/09-02/1017393c9591747933.jpg',
        title: '秒变861DW，快克2008改造教程！',
        metas: ['3万+浏览', '14学员', '0评分'],
        author: {
          avatar:
            'http://image.howzhi.com/user/2017/09-02/100848095bd2865648.jpg',
          name: '迅维网校',
          isVip: false
        },
        price: '免费'
      },
      {
        image:
          'http://image.howzhi.com/course/2017/06-19/1507528139c8690838.png',
        title: 'Data Knows | 小D数据分析课',
        metas: ['原创', '2万+浏览', '25学员', '5评分'],
        author: {
          avatar:
            'http://image.howzhi.com/user/2017/05-12/16304117bc74343604.jpg',
          name: '第一财经数据商学院',
          isVip: false
        },
        price: '免费'
      }
    ]
    // const cate = await Category.findOne({ name: '国内大学' })
    const cate = await Category.findOne({ _id: '5f7ae17ac5bed119e4e981ac' })
    const formData = rawData.map((v) => {
      v.price = v.price.match(/\d/)
        ? parseFloat(v.price.match(/\d+(\.\d+)?/)[0])
        : 0
      v.readed = v.metas[v.metas.length - 3].includes('万')
        ? parseFloat(v.metas[v.metas.length - 3]) * 10000 +
          Math.floor(Math.random() * 10000)
        : parseFloat(v.metas[v.metas.length - 3])
      v.students = parseFloat(v.metas[v.metas.length - 2])
      v.score = parseFloat(v.metas[v.metas.length - 1])
      v.category = cate._id
      // v.author.name = v.author.name || '该账户以注销'
      delete v.metas
      return v
    })
    console.log(formData)
    await Course.deleteMany({})
    // await Course.insertMany(formData)
    res.send(formData)
  })

  // 获取班级数据的测试接口
  app.get('/init/class', async (req, res) => {
    const rawData = [
      {
        title: '零基础摄影入门班',
        desc:
          '好知摄影入门班，最有趣的单反摄影入门教程！零基础学习摄影入门技巧，专业摄影师为你...',
        students: 27,
        times: 32,
        homeworks: 6,
        hours: 24,
        image:
          'http://image.howzhi.com/default/2016/02-18/1151026a9542216720.jpg'
      },
      {
        title: '极致风光摄影进阶提高班',
        desc:
          '华盖 500PX签约摄影师独家风光后期秘诀。从入门到提高，系统地学习前期拍摄技术...',
        students: 25,
        times: 44,
        homeworks: 7,
        hours: 24,
        image:
          'http://image.howzhi.com/default/2016/03-18/113139b0d161061610.jpg'
      },
      {
        title: 'Adobe Lightroom cc后期基础入门班',
        desc: '每天10min 轻松入门',
        students: 91,
        times: 59,
        homeworks: 5,
        hours: 24,
        image:
          'http://image.howzhi.com/default/2015/11-30/10434959afa2686578.jpg'
      },
      {
        title: '牛牛人像摄影班',
        desc:
          '人像摄影可以是怎样的？它可以是日系清新人像：清淡的色调，简单的画面，不经意间的构...',
        students: 58,
        times: 30,
        homeworks: 0,
        hours: 24,
        image:
          'http://image.howzhi.com/default/2016/04-08/144103f87e49421080.jpg'
      }
    ]
    const Classroom = require('../../models/Classroom')
    await Classroom.deleteMany({})
    await Classroom.insertMany(rawData)
    res.send(rawData)
  })

  // 获取话题数据的测试接口
  app.get('/init/topic', async (req, res) => {
    const rawData = [
      {
        image: 'http://image.howzhi.com/system/block_picture_1521085976.jpg',
        title: '【招聘】售前客服（2名）',
        username: '知了',
        time: '2018-03-15'
      },
      {
        image: 'http://image.howzhi.com/system/block_picture_1483955463.jpg',
        title: '韩剧《鬼怪》男一二都在狠狠健身 裸裸的圈粉啊',
        username: '健身小飞侠',
        time: '2017-01-09'
      },
      {
        image: 'http://image.howzhi.com/system/block_picture_1473303419.jpg',
        title: 'Bruno Aveillan的虚幻光影',
        username: '猪脚好咸',
        time: '2016-09-06'
      },
      {
        image: 'http://image.howzhi.com/system/block_picture_1473300683.jpg',
        title: 'iPhone 7来了，要不要买买买？',
        username: '乱流',
        time: '2016-09-08'
      },
      {
        image: 'http://image.howzhi.com/system/block_picture_1472785605.jpg',
        title: '20分钟=跑步一小时？什么运动这么牛！',
        username: '三尺青锋',
        time: '2016-09-02'
      },
      {
        image: 'http://image.howzhi.com/system/block_picture_1470382807.jpg',
        title: '如何品鉴单品咖啡',
        username: '卷卷',
        time: '2016-08-05'
      },
      {
        image: 'http://image.howzhi.com/system/block_picture_1496885430.jpg',
        title: '【招募】这个每年走数百里山路助学的公益人需要你的帮助',
        username: '乱流',
        time: '2017-06-08'
      },
      {
        image: 'http://image.howzhi.com/system/block_picture_1463035061.jpg',
        title: '一个自由摄影师的五年创业之路：从苦逼到牛逼——专访牛牛很忙',
        username: '曹佳佳的熊猫眼',
        time: '2016-05-12'
      },
      {
        image: 'http://image.howzhi.com/system/block_picture_1462331991.jpg',
        title: '看薇薇安·麦尔是如何观察这个世界的',
        username: '猪脚好咸',
        time: '2016-05-04'
      },
      {
        image: 'http://image.howzhi.com/system/block_picture_1461318544.jpg',
        title: '【作品欣赏】青山裕企的那些少女们',
        username: '猪脚好咸',
        time: '2016-04-22'
      },
      {
        image: 'http://image.howzhi.com/system/block_picture_1457857515.jpg',
        title: 'Llightroom预设资源分享（第一期）',
        username: '乱流',
        time: '2015-03-13'
      }
    ]
    const Topic = require('../../models/Topic')
    await Topic.deleteMany({})
    await Topic.insertMany(rawData)
    res.send(rawData)
  })

  // 获取标签数据的测试接口
  app.get('/init/tag', async (req, res) => {
    const rawData = [
      {
        image: 'http://www.howzhi.com/themes/howzhi/img/tag/tag1.jpg?7.5.15.6',
        name: 'Lightroom',
        numbers: 12
      },
      {
        image: 'http://www.howzhi.com/themes/howzhi/img/tag/tag2.jpg?7.5.15.6',
        name: 'Photoshop',
        numbers: 100
      },
      {
        image: 'http://www.howzhi.com/themes/howzhi/img/tag/tag3.jpg?7.5.15.6',
        name: 'After',
        numbers: 15
      },
      {
        image: 'http://www.howzhi.com/themes/howzhi/img/tag/tag4.jpg?7.5.15.6',
        name: '吉他',
        numbers: 72
      },
      {
        image: 'http://www.howzhi.com/themes/howzhi/img/tag/tag5.jpg?7.5.15.6',
        name: '人像摄影',
        numbers: 52
      },
      {
        image: 'http://www.howzhi.com/themes/howzhi/img/tag/tag6.jpg?7.5.15.6',
        name: '产品摄影',
        numbers: 30
      },
      {
        image: 'http://www.howzhi.com/themes/howzhi/img/tag/tag7.jpg?7.5.15.6',
        name: '摄影布光',
        numbers: 26
      },
      {
        image: 'http://www.howzhi.com/themes/howzhi/img/tag/tag8.jpg?7.5.15.6',
        name: '3d制作',
        numbers: 64
      },
      {
        image: 'http://www.howzhi.com/themes/howzhi/img/tag/tag9.jpg?7.5.15.6',
        name: '风光摄影',
        numbers: 41
      },
      {
        image: 'http://www.howzhi.com/themes/howzhi/img/tag/tag10.jpg?7.5.15.6',
        name: '办公软件',
        numbers: 31
      },
      {
        image: 'http://www.howzhi.com/themes/howzhi/img/tag/tag11.jpg?7.5.15.6',
        name: '手工制作',
        numbers: 32
      },
      {
        image: 'http://www.howzhi.com/themes/howzhi/img/tag/tag12.jpg?7.5.15.6',
        name: '音频制作',
        numbers: 12
      }
    ]
    const Tag = require('../../models/Tag')
    await Tag.deleteMany({})
    await Tag.insertMany(rawData)
    res.send(rawData)
  })

  // 获取小组数据的测试接口
  app.get('/init/group', async (req, res) => {
    const Category = require('../../models/Category')
    const Group = require('../../models/Group')
    const currentcate = await Category.findOne({ name: '公开课' })
    const rawData = [
      {
        image:
          'http://image.howzhi.com/group-icon/2013/08-10/14363538f209109369.jpg',
        title: '高中生活我做主(>^...',
        data: '78个成员 \n      2942个话题'
      },
      {
        image:
          'http://image.howzhi.com/group-icon/2013/04-01/105943fe47e1187483.jpg',
        title: '理科生',
        data: '168个成员 \n      1369个话题'
      },
      {
        image:
          'http://image.howzhi.com/group-icon/2012/07-28/031627ba7b1a644545.jpg',
        title: '解体概要',
        data: '226个成员 \n      1456个话题'
      },
      {
        image:
          'http://image.howzhi.com/group-icon/2011/11-16/1151175e2fc5261920.jpg',
        title: '名校公开课',
        data: '958个成员 \n      2994个话题'
      }
    ]
    const groupData = rawData.map((v) => {
      return {
        image: v.image,
        title: v.title,
        number: v.data.match(/(\d+)个成员/)[1] * 1,
        topic: v.data.match(/(\d+)个话题/)[1] * 1,
        category: currentcate._id
      }
    })
    // Group.deleteMany({})
    Group.insertMany(groupData)
    res.send(groupData)
  })

  // 获取热门话题的测试接口
  app.get('/init/hot/topic', async (req, res) => {
    const rawData = [
      {
        category: '摄影公社',
        title: '这11张照片讲述了摄影演变史',
        image:
          'http://image.howzhi.com/avatar/2014/11-25/1359131e28a9803288.jpg',
        username: '曹佳佳的熊猫眼',
        time: '2015-12-18',
        lastReply: { user: '滴兔滴', time: '08-14' },
        reply: '25'
      },
      {
        category: '摄影公社',
        title: '各大摄影网站收集',
        image:
          'http://image.howzhi.com/avatar/2014/11-25/1359131e28a9803288.jpg',
        username: '曹佳佳的熊猫眼',
        time: '2015-12-10',
        lastReply: { user: '就是兔子', time: '2016-01-15' }
      },
      {
        category: '摄影公社',
        title: 'Flickr公布2015年最受欢迎作品和相机',
        image:
          'http://image.howzhi.com/default/2015/07-14/145733d2af26635228.jpg',
        username: '乱流',
        time: '2015-12-08',
        lastReply: { user: '乱流', time: '2016-12-09' },
        reply: '9'
      },
      {
        category: '摄影公社',
        title: '自然风光摄影之美',
        image:
          'http://image.howzhi.com/avatar/2014/11-25/1359131e28a9803288.jpg',
        username: '曹佳佳的熊猫眼',
        time: '2015-11-18',
        lastReply: { user: '曹佳佳的熊猫眼', time: '2018-06-07' },
        reply: '5'
      },
      {
        category: '摄影公社',
        title: 'Elena Shumilova 温情人像摄影 | 记录成长',
        image:
          'http://image.howzhi.com/avatar/2014/11-25/1359131e28a9803288.jpg',
        username: '曹佳佳的熊猫眼',
        time: '2015-11-10',
        lastReply: { user: 'haozhi001', time: '05-12' },
        reply: '2',
        isGood: '精'
      },
      {
        category: '摄影公社',
        title: '2015索尼世界摄影奖优秀作品',
        image:
          'http://image.howzhi.com/default/2015/07-14/145733d2af26635228.jpg',
        username: '乱流',
        time: '2015-11-05',
        lastReply: { user: '乱流', time: '2018-06-07' },
        reply: '7'
      },
      {
        category: '摄影公社',
        title: '一小时一张照片：CBRE 摄影大奖揭露世界24 小时城市生活',
        image:
          'http://image.howzhi.com/default/2015/07-14/145733d2af26635228.jpg',
        username: '乱流',
        time: '2015-10-30',
        lastReply: { user: '2442517155', time: '2018-08-12' },
        reply: '3'
      },
      {
        category: '每月养成一个好习惯',
        title: '读书，是门槛最低的高贵',
        image:
          'http://image.howzhi.com/default/2015/08-18/105314a08257003939.jpeg',
        username: '栗子·七',
        time: '2015-10-27',
        lastReply: { user: '2442517155', time: '2018-09-08' },
        reply: '3'
      },
      {
        category: '程序员大本营',
        title: '【转】黑客马拉松',
        image:
          'http://image.howzhi.com/default/2015/07-10/00235285617b530342.jpg',
        username: '王讨厌丶',
        time: '2015-10-26',
        lastReply: { user: '2442517155', time: '2018-09-03' },
        reply: '4'
      },
      {
        category: 'DIY手工王国',
        title: '【DIY手工制作方法教程】自制超有情调的水蜡烛',
        image:
          'http://image.howzhi.com/default/2015/08-12/1741084708ee620252.jpg',
        username: '梦阑珊',
        time: '2015-10-23',
        lastReply: { user: '2442517155', time: '2018-08-20' },
        reply: '2'
      },
      {
        category: '下午茶',
        title: '今夏最in吃法，冰激凌配鸡蛋仔',
        image:
          'http://image.howzhi.com/avatar/2015/07-08/22500800974f867554.jpg',
        username: '卷卷',
        time: '2015-08-19',
        lastReply: { user: '千与千', time: '2015-08-21' },
        reply: '2'
      },
      {
        category: '好知大本营（教务处）',
        title: '【好知七夕活动】晒出你为TA拍出的最美瞬间',
        image:
          'http://image.howzhi.com/default/2015/08-21/10185820d1de307551.jpg',
        username: '就是兔子',
        time: '2015-08-18',
        lastReply: { user: 'zhujiash', time: '2016-06-02' },
        reply: '17'
      },
      {
        category: '摄影公社',
        title: '推荐一个在线处理照片胶片感的网站',
        image:
          'http://image.howzhi.com/avatar/2013/01-28/1626488aa9fa594123.jpg',
        username: '了了',
        time: '2015-08-11',
        lastReply: { user: '追糖浆的阿鲍', time: '2018-01-26' },
        reply: '6'
      },
      {
        category: '摄影公社',
        title: 'FAPA摄影奖冠军作品欣赏',
        image:
          'http://image.howzhi.com/default/2015/07-14/145733d2af26635228.jpg',
        username: '乱流',
        time: '2015-08-04',
        lastReply: { user: '2442517155', time: '2018-09-16' },
        reply: '7'
      },
      {
        category: '好知大本营（教务处）',
        title: '【摄影大吐槽】吐槽摄影乱象，赢好知8月班学习基金',
        image:
          'http://image.howzhi.com/avatar/2013/05-10/1453371e5503236335.jpg',
        username: '知了',
        time: '2015-07-30',
        lastReply: { user: '泉木', time: '2015-12-25' },
        reply: '110',
        isGood: '精'
      },
      {
        category: '产品经理',
        title: 'Win10安装简述和简单功能使用',
        image: 'http://www.howzhi.com/assets/img/default/avatar.png',
        username: 'shunqin2350',
        time: '2015-07-30',
        lastReply: { user: '懒人', time: '2015-07-31' },
        reply: '2'
      },
      {
        category: '摄影公社',
        title: '从前，现在。',
        image:
          'http://image.howzhi.com/default/2015/07-23/200707b36596421327.jpg',
        username: '纪然',
        time: '2015-07-23',
        lastReply: { user: '冷风有信', time: '2017-03-28' },
        reply: '8',
        isGood: '精'
      },
      {
        category: 'Photoshop照片后期处理学习交流',
        title: '教你打造花千骨梦幻剧照海报',
        image:
          'http://image.howzhi.com/default/2015/07-14/145733d2af26635228.jpg',
        username: '乱流',
        time: '2015-07-23',
        lastReply: { user: 'allen晓江', time: '2015-10-11' },
        reply: '5'
      },
      {
        category: '摄影公社',
        title: '不能跟你在一起，即便晴天又何妨。',
        image:
          'http://image.howzhi.com/default/2016/04-20/231108c219f5981861.jpg',
        username: 'JmrBrave',
        time: '2015-07-21',
        lastReply: { user: '2442517155', time: '2018-08-20' },
        reply: '4'
      },
      {
        category: '摄影公社',
        title: '光与色的艺术',
        image:
          'http://image.howzhi.com/default/2015/07-14/145733d2af26635228.jpg',
        username: '乱流',
        time: '2015-07-21',
        lastReply: { user: '光影有梦', time: '2015-07-24' },
        reply: '2'
      },
      {
        category: '好知大本营（教务处）',
        title: '好知网安卓移动端升级版已发布',
        image:
          'http://image.howzhi.com/avatar/2013/05-10/1453371e5503236335.jpg',
        username: '知了',
        time: '2015-07-15',
        lastReply: { user: 'acc07', time: '2015-09-05' },
        reply: '1'
      },
      {
        category: '摄影公社',
        title: '摄影频道【热门作品】征集中',
        image:
          'http://image.howzhi.com/default/2015/07-14/145733d2af26635228.jpg',
        username: '乱流',
        time: '2015-07-13',
        lastReply: { user: '涛yt', time: '2015-08-22' },
        reply: '6'
      },
      {
        category: '好知大本营（教务处）',
        title: '【我+好知=我们】好知故事的“后续”',
        image:
          'http://image.howzhi.com/avatar/2013/05-10/1453371e5503236335.jpg',
        username: '知了',
        time: '2015-07-08',
        lastReply: { user: '知了', time: '2015-08-06' },
        reply: '22'
      },
      {
        category: '好知大本营（教务处）',
        title: '【内测班签到帖】摄影1班成员列队签到啦！',
        image:
          'http://image.howzhi.com/avatar/2013/05-10/1453371e5503236335.jpg',
        username: '知了',
        time: '2015-07-03',
        lastReply: { user: 'zhujiash', time: '2016-06-02' },
        reply: '172'
      },
      {
        category: '我们提前N时上床，一起读书',
        title: '人生马拉松',
        image:
          'http://image.howzhi.com/avatar/2013/11-16/132652c9c199357869.jpg',
        username: '弦之妤',
        time: '2015-07-02',
        lastReply: { user: '弦之妤', time: '2015-07-02' }
      }
    ]
    const Topic = require('../../models/Topic')
    const hotTopic = rawData.map((v) => {
      v.reply = typeof v.reply === 'string' ? v.reply * 1 : null
      v.isGood = typeof v.isGood === 'string' ? true : false
      return v
    })
    Topic.insertMany(hotTopic)
    res.send(hotTopic)
  })

  // 获取 二级分类 的接口
  app.get('/admin/api/get/secCate', async (req, res) => {
    const Category = require('../../models/Category')
    const parent = await Category.aggregate([
      { $match: { name: { $in: ['班级', '课程', '小组'] } } }
    ])
    const parentId = parent.map((v) => v._id)
    const secCate = await Category.aggregate([
      { $match: { parent: { $in: parentId } } }
    ])
    const newData = {
      parentCate: parent,
      childCate: secCate
    }
    res.send(newData)
  })

  // 获取次级分类下的课程
  app.get('/admin/api/get/courseById/:id', async (req, res) => {
    const Category = require('../../models/Category')
    const Course = require('../../models/Course')
    const categories = await Category.find({ parent: req.params.id })
    const catesArr = categories.map((v) => v._id)
    const courses = await Course.aggregate([
      { $match: { category: { $in: catesArr } } },
      {
        $lookup: {
          from: 'categories',
          localField: 'category',
          foreignField: '_id',
          as: 'category'
        }
      }
    ])
    const newData = courses.map((v) => {
      v.key = v._id
      return v
    })
    res.send(newData)
  })

  // 通过子级分类找父级分类
  app.get('/admin/api/get/parentCate/:id', async (req, res) => {
    const Category = require('../../models/Category')
    const Course = require('../../models/Course')
    const course = await Course.findOne({ _id: req.params.id })
    const childCate = await Category.findOne({ _id: course.category })
    const parentCate = await Category.findOne({ _id: childCate.parent })
    res.send(parentCate)
  })

  // 上传图片文件的处理
  app.post('/admin/api/upload', upload.single('file'), async (req, res) => {
    const file = req.file
    console.log(file)
    file.url = `http://localhost:5000/uploads/${file.filename}`
    res.send(file)
  })
}

// 获取数据的方法
// JSON.stringify(
//   $$('.col-md-9 .course .course-item .course-img img').map((item, index) => {
//     return {
//       image: item.src,
//       title: $$('a', $$('.course-info>.title')[index]).map((v) => {
//         return v.textContent
//       })[0],
//       metas: $$('span', $$('.course-info>.metas')[index]).map((v) => {
//         return v.textContent
//       }),
//       author: $$('.teacher', $$('.col-md-9>.course-info')[index]).map((v) => {
//         return {
//           avatar: $$('.js-user-card>img', v).map((n) => n.src)[0],
//           name: $$('.js-user-card', v)
//             .map((n) => n.textContent)[0]
//             .trim(),
//           isVip: $$('.daren-icon-t', v).map((n) => n.title)[0] ? true : false
//         }
//       })[index],
//       price: $$('.price>span', $$('.col-md-9>.course-info>.teacher')[index])
//         .map((v) => {
//           return v.textContent
//         })
//         [index].trim()
//     }
//   })
// )
